﻿@using FloodFree.Common;

@model FloodFree.Web.ViewModels.CityShowViewModel

@{
    ViewBag.Title = "Cities - " + Model.City.Name;
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">


    var map;

    handlerSubscribe = function (e) {
        var btnHtml = e.target.outerHTML;
        var sensorid = $(btnHtml).data('sensorid');
        var dataString = "SensorId=" + sensorid;
        var infoboxAction = $('.infobox-actions-list');
        infoboxAction.html('Carregando...');
        $.ajax({
            type: "POST",
            url: "/Subscriptions/Create",
            data: dataString,
            cache: false,
            dataType: "json",
            success: function (data) {
                infoboxAction.html(data.Message);
                //alert(data.Message);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //document.location = "/Account/LogOn?ReturnUrl=/";
                infoboxAction.html('Problema ao enviar requisição');
            },
            complete: function () {
                // enable the inputs
                //alert('Complete');
            }
        });
    }

    displayEventInfo = function (e) {
        //var infoboxOptions = { showPointer: false, title: e.target.City, description: e.target.Address, actions: [{ label: "<span data-sensorid='" + e.target.SensorId + "'>Receber atualizações</span>", eventHandler: handlerSubscribe}]};
        console.log(e.pageX);
        var infoboxOptions = { showPointer: false, title: e.target.City, description: e.target.Address };

        var defaultInfobox = new Microsoft.Maps.Infobox(map.getCenter(), infoboxOptions);


        window.map.entities.push(defaultInfobox);
        var actions = defaultInfobox.getActions();
        var actionStr = '';
        for (var cnt = 0; cnt < actions.length; cnt++) {
            actionStr = actionStr + '<b> label-</b>' + actions[cnt].label + '<br><b>handler-</b>' + actions[cnt].eventHandler + '<br>'
        }
    }

    $(document).ready(function () {
        window.map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), { credentials: "ArrFQB1Lfu6u47_1CR7QJMMV_o-EcNBFYkql63-qieAdx_3YzNHq9FdnEdaamOu7" });
        $(".menu-loc-item").click(function () {

            window.map.entities.clear(); 

            var lati = $(this).data("latitude");
            var long = $(this).data("longitude");
            var sensorid = $(this).data("id");
            var city = $(this).data("city");
            var address = $(this).data("address");
            var status = $(this).data("status");


            window.map.entities.clear();
            if (lati !== null && long !== null) {
                window.map.setView({ zoom: 14, center: new Microsoft.Maps.Location(lati, long) })
                var pushpinOptions = null;
                if (status == 0) {
                    pushpinOptions = { icon: '/Content/img/poi_search_green.png', width: 30, height: 50 };
                } else {
                    pushpinOptions = { icon: '/Content/img/poi_search_red.png', width: 30, height: 50 };
                }
                var pushpin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(lati, long), pushpinOptions);
                pushpin.SensorId = sensorid;
                pushpin.City = city;
                pushpin.Address = address;
                pushpinClick = Microsoft.Maps.Events.addHandler(pushpin, 'click', displayEventInfo);
                pushpinClick.sensor = 10;
                window.map.entities.push(pushpin);
            }
        });


        $(".menu-loc-action-item-unsubscribe").click(function () {
            var subLink = $(this);
            var subId = $(this).data("subid");
            var dataString = 'SubscriptionId=' + subId;
            $("*").css("cursor", "wait");
            $.ajax({
                type: "DELETE",
                url: "/Subscriptions/Delete",
                data: dataString,
                cache: false,
                dataType: "json",
                success: function (data) {
                    subLink.replaceWith(data.Message);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    //document.location = "/Account/LogOn?ReturnUrl=/";
                    alert('Problema ao enviar requisição');
                },
                complete: function () {
                    // enable the inputs
                    //alert('Complete');
                    $("*").css("cursor", "");
                }
            });
        });

        $(".menu-loc-action-item-subscribe").click(function () {
            var subLink = $(this);
            var sensorId = $(this).data("sensorid");
            var dataString = 'SensorId=' + sensorId;
            $("*").css("cursor", "wait");
            $.ajax({
                type: "POST",
                url: "/Subscriptions/Create",
                data: dataString,
                cache: false,
                dataType: "json",
                success: function (data) {
                    subLink.replaceWith(data.Message);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    //document.location = "/Account/LogOn?ReturnUrl=/";
                    alert('Problema ao enviar requisição');
                },
                complete: function () {
                    $("*").css("cursor", "");
                    // enable the inputs
                    //alert('Complete');
                }
            });
        });
    });

  

</script>
<div id="wrapper" class="wrapper">
    <div class="menu">
        <div class="top-menu">
            @if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                <a href="/Account/LogOn?ReturnUrl=/">Login</a>
            }
            else
            {
                <a href="/Account/LogOff?ReturnUrl=/">Logoff</a>
            }
        </div>
        <div class="head">
            <h1><a href="/">FloodFree</a></h1>
            <h2>@Model.City.Name</h2>
        </div>
        <div class="body">
            <ul class="menu-localizations">
                @if (Model.City.Sensors.Count > 0)
                {
                    foreach (Sensor s in Model.City.Sensors)
                    {
                        <li class="menu-localizations-item"><a href="#" class="menu-loc-item" data-latitude="@s.Latitude" data-longitude="@s.Longitude" data-id="@s.SensorId" data-city="@Model.City.Name" data-address="@s.Address" data-status="@(s.Updates.Count > 0 ? s.Updates.OrderByDescending(d => d.Date).FirstOrDefault().Status : 0)">
                                <strong>@s.Address</strong>
                                @if (s.Updates.Count > 0)
                                {
                                    <span>@s.Updates.OrderByDescending(d => d.Date).FirstOrDefault().Date.ToString("dd/MM/yyyy")</span>
                                }
                            </a>
                            <ul class="menu-loc-item-actions">
                            @{Subscription sub = null;}
                            @if (HttpContext.Current.User.Identity.IsAuthenticated)
                            {

                                if (Model.Subscriptions != null && Model.Subscriptions.Count > 0)
                                {
                                    
                                    sub = (from Subscription s1 in Model.Subscriptions
                                           where s1.SensorId.Equals(s.SensorId)
                                           select s1).FirstOrDefault();
                                }

                                if (sub != null)
                                {
                                    <li><span class="menu-loc-action-item-unsubscribe" data-subid='@sub.Id'>Remover inscrição</span></li>
                                }
                                else
                                {
                                    <li><span class="menu-loc-action-item-subscribe" data-sensorid='@s.SensorId'>Inscrever</span></li>
                                }
                            }
                            </ul>
                        </li>
                    }
                }
                else
                {
                    <li><a href="#">No sensors available</a></li>
                }
                
            </ul>
        </div>
    </div>
    <div class="content">
        <div class="body">
            <div id='mapDiv' style="position: relative; width: 777px; height: 600px;">
            </div>
        </div>
    </div>
    <div class="footer">
    </div>
</div>
